<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<canvas id="canvas" width="500" height="400" style="background:#000;"></canvas>
	</body>
</html>

   <script src="utils.js"></script>
   <script src="ball.js"></script>
   <script>
        window.onload = function(){
            var canvas = document.getElementById('canvas'),
                context = canvas.getContext('2d'),
                ball = new Ball(40, "red");
            
            var xpos = 0, //初始化3D坐标
                ypos = 0,
                zpos = 0,
                vx = 0,      //初始化3D速度
                vy = 0,
                vz = 0,
                friction = 0.98,
                fl = 250,
                vpX = canvas.width/2,        //消失点
                vpY = canvas.height/2;
            
            //按键控制
            window.addEventListener('keydown', function(e){
                switch (e.keyCode){
                    case 38:      //up
                        vy -= 1;
                        break;
                    case 40:      //down
                        vy += 1;
                        break;
                    case 37:      //left
                        vx -= 1;
                        break;
                    case 39:      //right
                        vx += 1;
                        break;
                    case 16:     //shift
                        vz += 1;
                        break;
                    case 17:     //control
                        vz -= 1;
                        break;    
                }
            }, false);
            
            //动画循环
            (function drawFrame(){
                window.requestAnimationFrame(drawFrame, canvas);
                context.clearRect(0, 0, canvas.width, canvas.height);
                
                xpos += vx;     //位置变化
                ypos += vy;
                zpos += vz;
                
                vx *= friction;
                vy *= friction;
                vz *= friction;
                
                //三维环境设置
                if(zpos > -fl){
                    var scale = fl/(fl+zpos);
                    ball.scaleX = ball.scaleY = scale;
                    ball.x = vpX + xpos*scale;
                    ball.y = vpY + ypos*scale;
                    ball.visible = true;
                }else{
                    ball.visible = false;
                }
                //绘制小球
                if(ball.visible){
                    ball.draw(context);
                }
                
            }())
        }
    
    </script>